<?php

namespace app\admin\middleware;

use think\facade\Log;
use think\facade\Request as FacadeRequest;
use think\Request;
use think\Response;
use app\admin\model\AdminLog;
use app\admin\model\AuthRule as AuthRuleModel;
/**
 * 系统操作日志中间件
 * Class SystemLog.
 */
class SystemLogBase
{
    /**
     * 敏感信息字段，日志记录时需要加密.
     * @var array
     */
    protected $sensitiveParams = [
        'password',
        'confirm_password',
        'old_password',
        'phone',
        'mobile',
    ];

    public function handle(Request $request, \Closure $next)
    {
        $response = $next($request);
        $params = $request->param();
        if (isset($params['s'])) {
            unset($params['s']);
        }
        foreach ($params as $key => $val) {
            in_array($key, $this->sensitiveParams) && $params[$key] = '***********';
        }
        $module     = app('http')->getName();
        $controller = $request->controller();
        $action     = $request->action();
        $name = $module . '/' . $controller . '/' . $action;
        $explain = isset($params["explain"])?$params["explain"]:AuthRuleModel::where("name",$name)->value("title")??"";
        $method = strtolower($request->method());
        $url = $request->url();
        $res = $response->getContent();
        $res = json_decode($res,true);
        if ($request->isAjax()&&isset($res["code"])&&$res["code"]!=0) {
            if (in_array($method, ['post','put', 'delete'])) {
                $ip = FacadeRequest::ip();
                $data = [
                    'admin_id' => session('admin_id'),
                    'url' => $url,
                    'explain' => $explain,
                    'method' => $method,
                    'ip' => $ip,
                    'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                    'useragent' => $_SERVER['HTTP_USER_AGENT'],
                ];
                AdminLog::create($data);
            }
        }
        return $response;
    }
}
